package com.huaxin.hxcloud.work;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.SVGViewDTO;
import com.huaxin.common.cache.DiskCache;
import com.huaxin.common.tools.AppOperator;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.ProgressListener;
import com.huaxin.hxcloud.R;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author songxf
 *         created at 2017/7/25 10:39
 * @desc SVG  Fragment
 */

public class HxSvgShowFragment extends BaseFragment {
    public static final String TAG = "HxSvgShowFragment";
    //    @BindView(R.id.img)
    //    ImageView      mImg;
    //    @BindView(R.id.info1)
    //    TextView       mInfo1;
    //    @BindView(info2)
    //    TextView       mInfo2;
    //    @BindView(info3)
    //    TextView       mInfo3;
    //    @BindView(info4)
    //    TextView       mInfo4;
    //    @BindView(info5)
    //    TextView       mInfo5;
    //    @BindView(R.id.progressBar)
    //    ProgressBar    mProgressBar;
    //    @BindView(R.id.action_load)
    //    TextView       mActionLoad;
    //    @BindView(R.id.action_check)
    //    TextView       mActionCheck;
    //    @BindView(R.id.text_progress)
    //    RelativeLayout mTextProgress;
    //    @BindView(R.id.content)
    //    FrameLayout    mContent;

    private static final int state_unload  = 0x01;
    private static final int state_loading = 0x02;
    private static final int state_done    = 0x03; //查看
    private static final int state_update  = 0x04;
    @BindView(R.id.img)
    ImageView   mImg;
    @BindView(R.id.info1)
    TextView    mInfo1;
    @BindView(R.id.info2)
    TextView    mInfo2;
    @BindView(R.id.info3)
    TextView    mInfo3;
    @BindView(R.id.info4)
    TextView    mInfo4;
    @BindView(R.id.info5)
    TextView    mInfo5;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.action_load)
    TextView    mActionLoad;
    @BindView(R.id.action_check)
    TextView    mActionCheck;
    @BindView(R.id.text_progress)
    FrameLayout mTextProgress;
    @BindView(R.id.content)
    FrameLayout mContent;

    private int state = state_unload;
    private SVGViewDTO.SvgListBean mSvgListBean;
    private String                 mMvgUrl;
    private String                 mSvgHtml;
    private ProgressListener       mListener;

    private ViewHolder viewHolder;
    private String     mStatioCode;
    private Runnable   mRunnable;

    public static HxSvgShowFragment newInstance() {
        Bundle args = new Bundle();
        HxSvgShowFragment fragment = new HxSvgShowFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_svg_show;
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void initData() {
        mStatioCode = getArguments().getString(TAG);
        mListener = new ProgressListener() {
            @Override
            public void onProgress(long hasWrittenLen, long totalLen, boolean hasFinish) {
                if (mProgressBar != null && mActionLoad != null) {
                    updateState(state_loading, (int) (hasWrittenLen * 100 / totalLen));
                    if (hasFinish) {
                        updateState(state_done);
                    }
                }
            }
        };
    }


    public void setData(SVGViewDTO.SvgListBean svgListBean) {
        Log.d(TAG, "setData: ---->" + svgListBean.toString());
        updateView(svgListBean);
        Log.d(TAG, "setData: -11--->" + mSvgListBean.getFileCode());
        File[] files = new File(getContext().getExternalCacheDir().getPath()).listFiles();
        Log.d(TAG, "setData: " + files.length);
        //        if (files.length == 0) {
        //            updateState(state_unload);
        //            return;
        //        }
        updateState(state_unload);

        if (svgListBean.isExist()) {
            updateState(state_done);
        }

        //        for (int i = 0; i < files.length; i++) { //是否缓存中存在
        //            Log.d(TAG, "setData: " + files[i].getName());
        //            if ((mSvgListBean.getFileCode() + ".html").equals(files[i].getName())) {
        //                // updateState(state_done);
        //                svgStates.put(files[i].getName(),true);
        //            } else {
        //                // updateState(state_unload);
        //                svgStates.put(files[i].getName(),false);
        //
        //            }
        //        }
    }

    /**
     * 设置svg是否存在
     *
     * @param svgListBean
     */
    private Map<String, Boolean> svgStates = new HashMap<>();

    public void setSvgExist(SVGViewDTO.SvgListBean svgListBean) {
        File[] files = new File(getContext().getExternalCacheDir().getPath()).listFiles();
        Log.d(TAG, "setData: " + files.length);
        boolean isExist = false;
        for (int i = 0; i < files.length; i++) { //是否缓存中存在
            Log.d(TAG, "setData: " + files[i].getName());
            // updateState(state_done);
            // updateState(state_unload);
            isExist = (svgListBean.getFileCode() + ".html").equals(files[i].getName());
        }
        svgListBean.setExist(isExist);
    }


    /**
     * 显示数据
     *
     * @param svgView
     */

    private void updateView(SVGViewDTO.SvgListBean svgView) {
        mSvgListBean = svgView;
        mMvgUrl = svgView.getMvgUrl();
        mSvgHtml = DiskCache.getFileName(mMvgUrl).replaceAll(".mvg", ".html");
       // loadNetImg(mImg, svgView.getImgUrl());
        //修改默认加载图爿
        Glide.with(this).load(svgView.getImgUrl()).apply(new RequestOptions().placeholder(R.drawable.defult_icon_svg)).into(mImg);
        loadText(mInfo1, svgView.getViewName());
        // loadText("工艺类型：", info2, svgView.getCraftName());
        loadText("文件编码：", mInfo3, svgView.getFileCode());
        loadText("大小：", mInfo4, svgView.getFileSize());
        loadText("更新时间：", mInfo5, svgView.getCreateTime());
        // checkSVGFile(svgView.getFileCode(), svgView.getCreateTime());
    }

    private void updateState(int state) {
        updateState(state, 0);
    }

    /**
     * 根据SVG图 状态，显示Button 状态
     *
     * @param state
     * @param progress
     */
    private void updateState(int state, int progress) {
        this.state = state;
        switch (state) {
            case state_update:
                mProgressBar.setVisibility(View.GONE);
                mTextProgress.setSelected(false);
                mActionLoad.setText("更新");
                mActionLoad.setVisibility(View.VISIBLE);
                mActionCheck.setVisibility(View.GONE);
                break;
            case state_unload:
                mProgressBar.setVisibility(View.GONE);
                mTextProgress.setSelected(false);
                mActionLoad.setText("下载");
                mActionLoad.setVisibility(View.VISIBLE);
                mActionCheck.setVisibility(View.GONE);
                break;
            case state_done:
                mProgressBar.setVisibility(View.GONE);
                mTextProgress.setSelected(true);
                mActionLoad.setText("查看");
                mActionLoad.setVisibility(View.GONE);
                mActionCheck.setVisibility(View.VISIBLE);
                break;
            case state_loading:
                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.setProgress(progress);
                mActionLoad.setText(progress + "%");
                mActionLoad.setVisibility(View.VISIBLE);
                mActionCheck.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }


    @OnClick({R.id.action_check, R.id.text_progress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.action_check:
                showSVG();
                break;
            case R.id.text_progress:
                switch (state) {
                    case state_update:
                    case state_unload:
                        updateState(state_loading);
                        downLoad();
                        break;
                    case state_done: //查看
                        break;
                    case state_loading:
                        break;
                    default:
                        break;
                }
                break;
        }
    }

    /**
     * 下载SVG图，并且并把SVG,转换成HTML
     */
    Call<ResponseBody> SVGDownCall;

    public void downLoad() {
        SVGDownCall = HxTransmitRequestHelper.getRequestApi().downloadFile(mMvgUrl);
        Log.d(TAG, "downLoad: ---->" + SVGDownCall.request().url());
        SVGDownCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: ---->" + response.isSuccessful());
                Log.d(TAG, "onResponse: ---->" + response.message());
                Log.d(TAG, "onResponse: ---->" + response.code());
                if (response.body() != null) {
                    AppOperator.runOnThread(new Runnable() {
                        @Override
                        public void run() {
                            InputStream inputStream = response.body().byteStream();
                            long fileSize = response.body().contentLength();
                            Log.d(TAG, "run: ---->" + mSvgHtml);
                            boolean writtenToDisk = DiskCache.writeSVGFile(inputStream, mSvgHtml);
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "onFailure: ---->" + t);
            }
        });
        HxTransmitRequestHelper.addDownloadListener(SVGDownCall.request().url(), mListener);

    }

    /**
     * 显示SVG图
     */
    public void showSVG() {
        File file = new File(getContext().getExternalCacheDir(), mSvgListBean.getFileCode() + ".html");
        loadWebView(file);
    }

    /**
     * 加载webView
     *
     * @param file
     */
    private void loadWebView(File file) {
        if (viewHolder == null) {
            final View view = mInflater.inflate(R.layout.pop_svg, null);
            viewHolder = new ViewHolder(view);
            viewHolder.popWin = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            viewHolder.popWin.setAnimationStyle(R.style.mypopwindow_anim_style);
            viewHolder.svgBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    viewHolder.popWin.dismiss();
                }
            });
            viewHolder.webView.setVerticalScrollBarEnabled(false);
            viewHolder.webView.setHorizontalScrollBarEnabled(false);
            WebSettings settings = viewHolder.webView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);
            settings.setSupportZoom(true);
            settings.setAllowFileAccess(true);// 设置允许访问文件数据
            settings.setBuiltInZoomControls(true);
            settings.setDisplayZoomControls(false);

            viewHolder.webView.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                }
            });
            viewHolder.webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    /* 页面加载完成后加载svg文件 */
                    if (newProgress == 100) {
                        //                            Log.d("Zoes", "onProgressChanged");
                    }
                }

            });

            viewHolder.webView.addJavascriptInterface(new runLoadJavaScript(), "loadSvg");

        }
        if (viewHolder.svgHtml != mSvgHtml) {
            viewHolder.svgHtml = mSvgHtml;
            viewHolder.webView.loadUrl(Uri.fromFile(file).toString());
            viewHolder.tipLayout.setVisibility(View.VISIBLE);
        }

        viewHolder.popWin.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }


    /**
     * 执行js 接口
     */
    private class runLoadJavaScript {
        @JavascriptInterface
        public void runLoadSvgJavaScript() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    viewHolder.tipLayout.setVisibility(View.GONE);
                }
            });
            Log.d(TAG, "runLoadSvgJavaScript: " + mStatioCode + ",----," + mSvgListBean.getFileCode());
            requestSvg();
        }
    }


    /**
     * @desc
     * @author songxf
     * created at 2017/7/25 11:35
     */
    private void requestSvg() {
        Call<String> call = HxTransmitRequestHelper.getRequestApi().svgDataValue(mStatioCode, mSvgListBean.getFileCode());
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "runLoadSvgJavaScript:----> " + response.body());
                    viewHolder.webView.loadUrl("javascript:onReal('" + response.body() + "')");
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
            }
        });
    }


    public class ViewHolder {
        @BindView(R.id.web_view)
        WebView      webView;
        @BindView(R.id.svg_back)
        ImageView    svgBack;
        @BindView(R.id.tip_msg)
        TextView     tipMsg;
        @BindView(R.id.tip_layout)
        LinearLayout tipLayout;
        PopupWindow popWin;
        String      svgHtml;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

}
